package web.bio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Random;

public class Server {
	private static String ip="127.0.0.1";
	private static int port=7777;
	
	public static void main(String[] args) {
		try {
			ServerSocket server=new ServerSocket();
			SocketAddress address=new InetSocketAddress(ip, port);
			server.bind(address);
			new Thread(new ServerStartThread(server)).start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class ServerStartThread implements Runnable{
	private ServerSocket serverSocket;
	

	public ServerStartThread(ServerSocket serverSocket) {
		super();
		this.serverSocket = serverSocket;
	}

	@Override
	public void run() {
		while(true) {
			try {
				Socket accept = serverSocket.accept();
				new Thread(new ServerHandler(accept)).start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
}


class ServerHandler implements Runnable{
	
	private Socket socket;

	public ServerHandler(Socket socket) {
		super();
		this.socket = socket;
	}


	@Override
	public void run() {
		BufferedReader in=null;
		BufferedWriter out=null;
		try {
		 in=new BufferedReader(new InputStreamReader(socket.getInputStream()));	
		 out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		String s=null;
		while((s=in.readLine())!=null) {
			System.out.println("server -->我是服务端，接收到了客户端的信息："+s);
		}
		socket.shutdownInput();
		
		out.write("好好学习"+new Random().nextInt(1000));
		 out.flush();
		socket.shutdownOutput();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(in!=null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				in=null;
			}
			if(out!=null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				out=null;
			}
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				socket=null;
			}
			
		}
		
	}
	
}
